package com.limh.readers.widget.recyclerview.base

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.limh.readers.R

/**
 * Function:
 * author: limh
 * time:2017/7/28
 */
class ViewHolder(var context: Context, itemView: View) :
        RecyclerView.ViewHolder(itemView) {

    var mViews: SparseArray<View> = SparseArray()
    var mConvertView: View = itemView
    var mContext: Context = context


    companion object {
        fun createViewHolder(context: Context, itemView: View): ViewHolder {
            val holder = ViewHolder(context, itemView)
            return holder
        }

        fun createViewHolder(context: Context, parent: ViewGroup, layoutId: Int): ViewHolder {
            var itemView: View
            if (layoutId == R.layout.view_item_grid) {
                //网格布局下防止内容靠右
                itemView = LayoutInflater.from(context).inflate(layoutId, null)
            } else {
                //线性布局下防止match_parent 不起作用
                itemView = LayoutInflater.from(context).inflate(layoutId, parent, false)
            }
            val holder = ViewHolder(context, itemView)
            return holder
        }
    }

    fun <T : View> getView(viewId: Int): T {
        var view = mViews.get(viewId)
        if (view == null) {
            view = mConvertView.findViewById(viewId)
            mViews.put(viewId, view)
        }
        return view as T
    }

    fun getConvertView(): View {
        return mConvertView
    }

    fun setText(viewId: Int, text: String): ViewHolder {
        val tv = getView<View>(viewId) as TextView
        tv.text = text
        return this
    }

    fun setVisible(viewId: Int, visable: Int) {
        val view = getView<View>(viewId)
        view.visibility = visable
    }

}